<template>
  <div>
    <head-nev msg="黑马优购" :backState="true"></head-nev>
    <!-- 搜索输入框 -->
    <form action="/">
      <van-search
        v-model="searchValue"
        placeholder="请输入搜索关键词"
        show-action
        @input="onSearch"
        @cancel="onCancel"
        @clear="onClear"
        @search="onGoodsList"
      />
    </form>
    <!-- 历史记录,根据搜索框键入值判断是否保留 -->
    <div v-if="searchValue.length ==0 && localSearchHistory !== null? true : false ">
      <van-row>
        <van-col span="22">
          <span class="historyTitle">历史记录：</span>
        </van-col>
        <van-col span="2">
          <span class="iconfont icon-shanchu" @click="cleanHistory"></span>
        </van-col>
      </van-row>
      <van-row class="historyTags">
        <van-tag
          v-for="(item, index) in localSearchHistory"
          :key="index"
          class="historyTag"
          @click="tagTouch(item)"
        >{{item}}</van-tag>
      </van-row>
    </div>
    <!-- 搜索结果列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <van-cell
        v-for="item in searchResult"
        :key="item.goods_id"
        :title="item.goods_name"
        @click="showGoodsid(item.goods_id)"
      />
    </van-list>
            <!-- 底部 -->
    <foot-nav></foot-nav>
  </div>
</template>
<script>
import Vue from 'vue';
import { Toast } from 'vant';
Vue.use(Toast);
import { log } from "util";
export default {
  data() {
    return {
      searchValue: "",
      searchResult: [],
      loading: false,
      finished: false,
      error: false,
      searchHistory: [],
      localSearchHistory: []
    };
  },
  created() {
    this.getHistory();
  },
  methods: {
    //输入框内容改变时触发搜索功能
    async onSearch() {
      const { data: res } = await this.$http.get("goods/qsearch", {
        params: { query: this.searchValue }
      });
      this.searchResult = res.message;
      // console.log(res);
      // console.log(this.searchResult)
    },
    //输入完拍回车跳转至商品列表页面
    onGoodsList() {
    //如果搜索框无内容，敲击回车不跳转
    // console.log(this.searchValue);
      if (this.searchValue.length === 0) return;
      //保存搜索记录
        if (this.searchResult.length === 0) {
          Toast('您搜索的商品不存在');
          return
          };
      this.saveHistory()
      this.$router.push({
        path: "goodsList",
        name: "goodsList",
        params: { cateName: this.searchValue }
      });
    },
    //点击取消清空搜索框内容
    onCancel() {
      this.searchValue = "";
      this.searchResult = [];
      this.finished = false;
      this.getHistory();
    },
    //点击x号清空搜索框内容
    onClear() {
      this.searchValue = "";
      this.searchResult = [];
      this.finished = false;
      this.getHistory();
    },
    onLoad() {
      //如果搜索结果没值
      if (this.searchResult.length == 0) {
        this.loading = false;
      }
      //如果搜索框有值
      else {
        // 异步更新数据
        setTimeout(() => {
          // 加载状态结束
          this.loading = false;
          // 数据全部加载完成
          this.finished = true;
        }, 500);
      }
    },
    //将搜索过的值存入localStorage中
    saveHistory() {
      //如果localstorage中有搜索历史，先取出localstorage中储存的history放入searchHistory中
      if (localStorage.getItem("searchHistory") != null) {
        this.searchHistory = JSON.parse(localStorage.getItem("searchHistory"));
      }
      this.searchHistory.unshift(this.searchValue);
      //数组去重后转换格式存入localStorage
      this.searchHistory = Array.from(new Set(this.searchHistory));
      // console.log(this.searchHistory);
      localStorage.setItem("searchHistory", JSON.stringify(this.searchHistory));
    },
    //点击跳转到商品界面
    showGoodsid(id) {
    //保存搜索记录
      this.saveHistory();
      //点击某项搜索结果后跳转至详情页
      this.$router.push({ path: "details", name: "Details", params: { id } });
    },
    //从localStorage获取item
    getHistory() {
      this.localSearchHistory = JSON.parse(
        localStorage.getItem("searchHistory")
      );
    },
    //点击删除清除历史记录
    cleanHistory() {
      localStorage.removeItem("searchHistory");
      this.localSearchHistory = [];
      this.getHistory();
    },
    //点击历史记录跳转商品列表
    tagTouch(goodsName) {
      this.searchValue = goodsName;
       this.$router.push({
        path: "goodsList",
        name: "goodsList",
        params: { cateName: goodsName }
      });
    }
  }
};
</script>

<style>
.historyTitle {
  font-size: 14px;
  margin-left: 10px;
}
.historyTag {
  margin: 4px;
}
.historyTags {
  margin-left: 6px;
}
</style>